package com.xmh.reptile.service;

import cn.hutool.core.io.FileUtil;
import com.xmh.reptile.util.RedisMockUtil;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class NovelLidapolyService {

    public static int errorCount = 0;

    public static final String key = "万古至尊";

    public static long newPageNumber = Long.parseLong(String.valueOf(RedisMockUtil.get(key) == null ? 0 : RedisMockUtil.get(key)));

    public static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

    public static void wgzz() throws InterruptedException {
        StringBuilder sb = new StringBuilder();

        try {
            String url = "http://www.lidapoly.com/ldks/19749/";
            Document doc = Jsoup.connect(url).get();

            Elements list = doc.select("body > div.container > div.row.row-section > div > div:nth-child(4) > ul > li > a");
            for (Element element : list) {
                String href = element.attr("href");

                if (StringUtils.isEmpty(href)) {
                    continue;
                }

                String title = element.html();

                String number = extractNumbersFromString(title);

                if (StringUtils.isNotEmpty(number) && Integer.parseInt(number) < 220) {
                    continue;
                }
                System.out.println(title);
                sb.append("\n\n====== ").append(title).append(" =====\n\n");
                getDetailHtml(sb, "http://www.lidapoly.com" + href);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotEmpty(sb.toString())) {
            FileUtil.appendString(sb.toString(), new File("C:\\Users\\12425\\OneDrive\\桌面\\test" + simpleDateFormat.format(new Date()) + ".txt"), "UTF-8");
            RedisMockUtil.set(key, newPageNumber);
        }
    }

    private static void getDetailHtml(StringBuilder sb, String href) throws InterruptedException {
        Document detailDoc = callAgain(href);
        Element select = detailDoc.getElementById("content");
        sb.append(textHandle(select.html()));

        Elements nextPageElement = detailDoc.select("#container > div > div > div.reader-main > div:nth-child(2) > a:nth-child(5)");
        if (nextPageElement != null && nextPageElement.html().contains("页")) {
            String nextPageUrl = "http://www.lidapoly.com" + nextPageElement.attr("href");
            getDetailHtml(sb, nextPageUrl);
        }
        Thread.sleep(1000);
    }

    public static String extractNumbersFromString(String str) {
        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (Character.isDigit(ch)) {
                builder.append(ch);
            }
        }

        return builder.toString();
    }

    private static Document callAgain(String url) throws InterruptedException {
        try {
            Document doc = Jsoup.connect(url).get();
            errorCount = 0;
            System.out.println("success get url !!!");
            return doc;
        } catch (Exception e) {
            System.out.println("have a error, errorCount: " + (errorCount + 1));
            if (errorCount++ > 10) {
                throw new RuntimeException();
            }
            Thread.sleep(5000);
            return callAgain(url);
        }
    }

    private static String textHandle(String text) {
        String result = text.replace("&nbsp;", "");
        result = result.replace("<p class=\"Readpage\">(第1/2页)本章未完，请点击↓↓↓继续阅读</p>", "");
        result = result.replace("<p class=\"Readpage\">(第2/2页)本章未完，请点击↓↓↓继续阅读</p>", "");
        result = result.replace("<br>", "");
        result = result.replace("&amp;", "");

        String substringBetween = StringUtils.substringBetween(result, "<div", "div>");
        result = result.replace("<div" + substringBetween + "div>", "");

        return result;
    }

}
